package pCloud.acesscontrol;

import java.io.FileOutputStream;
import java.net.URI;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import pCloud.PCloudAttributeAndType;

import com.sun.xacml.Indenter;
import com.sun.xacml.attr.IntegerAttribute;
import com.sun.xacml.attr.StringAttribute;
import com.sun.xacml.ctx.Attribute;
import com.sun.xacml.ctx.RequestCtx;
import com.sun.xacml.ctx.ResponseCtx;
import com.sun.xacml.ctx.Result;
import com.sun.xacml.ctx.Subject;

public class RequestHelper {

	// for matching streamId and key
	public static RequestCtx createSimpleRequest(int streamId, int key)
			throws Exception {
		RequestCtx request = new RequestCtx(setupSubjects(key),
				setupResources(streamId), new HashSet(), new HashSet());
		request.encode(new FileOutputStream("request_0"), new Indenter());
		return request;

	}

	private static Set setupSubjects(int key) throws Exception {
		HashSet subjects = new HashSet();

		HashSet attributes = new HashSet();
		URI subjectName = new URI(PCloudAttributeAndType.SUBJECT_KEY_ID);
		IntegerAttribute subjectNameValue = new IntegerAttribute(key);
		attributes
				.add(new Attribute(subjectName, null, null, subjectNameValue));

		subjects.add(new Subject(attributes));
		return subjects;
	}

	private static Set setupResources(int streamId) throws Exception {
		HashSet resources = new HashSet();

		URI resourceID = new URI(PCloudAttributeAndType.RESOURCE_STREAM_ID);
		IntegerAttribute resourceValue = new IntegerAttribute(streamId);
		resources.add(new Attribute(resourceID, null, null, resourceValue));

		return resources;
	}

	public static void main(String[] args) throws Exception {
		PCloudPDP pdp = new PCloudPDP();
		PCloudPEP pep = new PCloudPEP(pdp);
		pdp.init();
		pdp.loadPolicy("policy_0_0");
		pdp.loadPolicy("policy_0_1");
		RequestCtx request = RequestHelper.createSimpleRequest(0, 10);
		pdp.setRequestCtx("request_0");
		ResponseCtx response = pdp.evaluate();
		Set results = response.getResults();
		Iterator it = results.iterator();
		while (it.hasNext()) {
			Result rs = (Result) it.next();
			if (rs.getDecision()==Result.DECISION_PERMIT)
				System.out.println("Matching policy = "+rs.getMatchingPolicyIds().get(0));
			else if (rs.getDecision()==Result.DECISION_INDETERMINATE){
				System.out.println("number of matching policies = "+rs.getMatchingPolicyIds().size());
				if (rs.getMatchingPolicyIds().size()>0)
					for (int i=0; i<rs.getMatchingPolicyIds().size(); i++)
						System.out.println("Matching policy = "+rs.getMatchingPolicyIds().get(i));
			}
			else
				System.out.println("No matching policy");
		}
	}
}
